﻿using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using System.Net;

public class ShopCell : MonoBehaviour {

	// Use this for initialization
	public static bool OnPay = false;
	public static string OrderUrl = "http://114.215.84.108:8080/card-datatransfer/order/create";
	public static string DetailUrl = "http://114.215.84.108:8080/card-datatransfer/weChatpay/appWechatPay";
	public string Id = "";
	public string Money = "";
	public string DiaMonds = "";
	private Text DiaMondsTxt = null;
	private Text MoneyTxt = null;
	private WWW www = null;
	private WWW www2 = null;
	void Start () {
		DiaMondsTxt = transform.GetChild (1).GetComponent<Text>();
		MoneyTxt = transform.GetChild (3).GetComponent<Text>();
		EventTriggerListener.Get (gameObject).onClick = BuyDiamonds;
		InvokeRepeating ("ResetImg", 1f, 0f);
	}

	private void ResetImg(){
		if (Id != "") {
			Sprite texture = (Sprite)Resources.Load("image/Shop/z"+Id,typeof(Sprite));
			transform.GetChild(0).GetChild(0).GetComponent<Image>().sprite = texture;
		}

	}

	private void ResetPay(){
		OnPay = false;
	}

	private void BuyDiamonds(GameObject go){
		if (OnPay) {
			return;
		}

		OnPay = true;

		InvokeRepeating ("ResetPay",5f,0f);
		string jsonStr = JsonUtility.ToJson (PayUitl.GetOrderJson(Id,info.UserInfo.UserData.id.ToString(),""));
		www = PayUitl.SengVisit (OrderUrl, jsonStr);
	}

	// Update is called once per frame
	void Update () {
		if ( Id != "" ) {
			DiaMondsTxt.text = DiaMonds + "钻";
			MoneyTxt.text = Money + "元";
		}
		if (www != null) {
			if ( www.isDone ) {
				MessageResultJson result =  JsonUtility.FromJson<MessageResultJson>(www.text);
				Debug.Log (result.orderId);
	
				string jsonStr = JsonUtility.ToJson (PayUitl.OrderDetailJson(result.orderId));
				www2 = PayUitl.SengVisit (DetailUrl, jsonStr);

				www.Dispose ();
				www = null;
			
			}
		}

		if (www2!= null) {
			if ( www2.isDone ) {
				
				Debug.Log (www2.text);
				PayRequestJson PayRequest =  JsonUtility.FromJson<PayRequestJson>(www2.text);
				www2.Dispose ();
				www2 = null;

				if (Application.platform == RuntimePlatform.Android) {
					AndroidWXTools.VisitWxPay (PayRequest);
				}
				if (Application.platform == RuntimePlatform.IPhonePlayer) {
					IOSWXTool.IOSWxPay (PayRequest.partnerId,PayRequest.prepayId,PayRequest.nonceStr,PayRequest.timeStamp,PayRequest.package,PayRequest.sign);
				}
			}
		}
	}
}